package carson.web.mvc.core.results;

import carson.web.mvc.core.exceptions.ResponseFileException;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;


/**
 * 根据文件路径将文件发送到响应
 *
 * @author Carson Chen
 */
public class FilePathResult extends AbstractFileResult {

    /**
     * 实例化FilePathResult
     *
     * @param filePath    文件路径
     * @param contentType 内容类型
     */
    public FilePathResult(String filePath, String contentType) {
        super(contentType);
        this.filePath = filePath;
    }

    /**
     * 实例化FilePathResult
     *
     * @param filePath         文件路径
     * @param contentType      内容类型
     * @param fileDownloadName 下载时的文件名称
     */
    public FilePathResult(String filePath, String contentType, String fileDownloadName) {
        super(contentType);
        this.filePath = filePath;
        setFileDownloadName(fileDownloadName);
    }

    private String filePath;

    /**
     * 获取文件路径
     *
     * @return 文件路径
     */
    public String getFilePath() {
        return filePath;
    }

    @Override
    protected void writeFile(HttpServletResponse response) throws Exception {
        String fileName;
        if (StringUtils.isEmpty(getFileDownloadName())) {
            File tempFile = new File(this.filePath);
            fileName = tempFile.getName();
        } else {
            fileName = getFileDownloadName();
        }
        try (FileInputStream in = new FileInputStream(this.filePath)) {
            response.setHeader("content-disposition", "attachment; filename="
                    + java.net.URLEncoder.encode(fileName, "UTF-8"));
            try (ServletOutputStream out = response.getOutputStream()) {
                StreamUtils.copy(in, out);
            }
        } catch (Exception e) {
            throw new ResponseFileException("导出文件异常", e);
        }
    }
}
